const http = require('http');
const url = require("url");
const mysql = require("mysql");
const config = require('./db/config.js')

let UserService = require("./service/UserService.js");
let AdService = require("./service/AdService.js")

const pool  = mysql.createPool(config);     //创建数据库连接

let userService = new UserService(pool);
let adService  =new AdService(pool);

http.createServer((request, response) => {
    //request是请求对象，包含了请求的所有数据；response是响应对象，包含了可能的所有的响应数据
    let urlParam = url.parse(request.url); //利用内置对象中的方法解析请求中的url
    //response.setHeader("Access-Control-Allow-Origin", "*"); //允许跨域访问
    response.setHeader('Content-Type', 'application/json');
    let jsonObject = null;
    //简单路由

    if(request.method =='GET'){
        console.log(urlParam);
        switch(urlParam.pathname){
            case '/user/login':
                if(urlParam.query){
                    let temp = urlParam.query.split("&");
                    let params = [];
                    temp.forEach(param=>{
                        params.push(param.split("=")[1]);
                    });
                    userService.login(response,params)
                }else{
                    response.end(JSON.stringify({result:'error',message:'请求参数错误'}));
                }
                break;
            case '/user/check':
                userService.checkUser(response,urlParam);
                break;
            case '/user/queryAll':
                userService.queryAll(response);
                break;
            case '/ad/getProvince':
                adService.getProvinces(response);
                break;
            case '/ad/getCity':
                //TODO:没有解决rest ful格式的url中请求参数的问题。
                if(urlParam.query){
                    console.log(urlParam.query);
                    let currentprovinceCode = urlParam.query.split('=')[1];
                    adService.getCities(response,currentprovinceCode);           
                }else{
                    response.end(JSON.stringify({result:'error',message:'请求参数错误'}));
                }
        }
    }
}).listen(3000);